package com.isljj.web_chat2.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isljj.web_chat2.config.OnlineUserManager;
import com.isljj.web_chat2.constant.Constant;
import com.isljj.web_chat2.mapper.*;
import com.isljj.web_chat2.model.*;
import com.isljj.web_chat2.utils.CookieUtils;
import com.isljj.web_chat2.utils.JWTUtils;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.IncorrectResultSetColumnCountException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class FriendContoller {


    @Autowired
    OnlineUserManager onlineUserManager;
    @Autowired
    FriendMapper friendMapper;
    @Autowired
    JWTUtils jwtUtils;
    @Autowired
    SessionMapper sessionMapper;
    @Autowired
    UserSessionMapper userSessionMapper;
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    FriendApplyMapper friendApplyMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CookieUtils cookieUtils;
    @RequestMapping("/refuseAddFriend")
    public  Result<Boolean> refuseAddFriend(Integer senderId,HttpServletRequest request){
//        todo 删除好友申请表内容
        String cookie = (request.getHeader("cookie"));
        //log.info(cookie);
        String jwtToken = cookieUtils.parseToken(cookie);
        //log.info(jwtToken);
        User loginUser = jwtUtils.getUserByToken(jwtToken);

        friendApplyMapper.delete(senderId,loginUser.getUserId());

        return new Result<>(200,"好友申请删除成功",true);
    }
//    同意申请 websocket
    @RequestMapping("/addFriend")
    public Result<Boolean> addFriend(Integer senderId,HttpServletRequest request) throws IOException {
        //拿到登录的id 和senderId 都插入好友表
        String cookie = (request.getHeader("cookie"));
        //log.info(cookie);
        String jwtToken = cookieUtils.parseToken(cookie);
        //log.info(jwtToken);
        User loginUser = jwtUtils.getUserByToken(jwtToken);

        //离线情况  增加一个新会
        // 新增一个回话 拿到回话id
        SessionLastMessage sessionLastMessage1 = new SessionLastMessage();
        sessionMapper.addASession(sessionLastMessage1);
        int sessionId = sessionLastMessage1.getSessionId();
//       //关系表
        userSessionMapper.add(sessionId,loginUser.getUserId());
        userSessionMapper.add(sessionId,senderId);
        Message message = new Message();
        message.setContent("我已经通过好友申请,可以开始聊天了!");
        message.setSessionId(sessionId);
        message.setFromId(loginUser.getUserId());
        messageMapper.insertMessage(message);
        WebSocketSession webSocketSession1 = onlineUserManager.getSession(loginUser.getUserId());

        WSAddFriendResponse wsAddFriendResponse = new WSAddFriendResponse();
        wsAddFriendResponse.setSessionId(sessionId);
        wsAddFriendResponse.setFromName(loginUser.getUserName());
        //再看对方在不在线 如果在线 马上转发
        WebSocketSession webSocketSession = onlineUserManager.getSession(senderId);
        if(webSocketSession!=null){
            //log.error("测试2!!!!");
            webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsAddFriendResponse)));
        }
        //给自己发一下
        wsAddFriendResponse.setFromId(senderId);
        wsAddFriendResponse.setFromName(userMapper.selectByUserId(senderId).getUserName());
        //log.error(onlineUserManager.toString());
        webSocketSession1.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsAddFriendResponse)));

//       //删除好友申请列表的对应消息
        friendApplyMapper.delete(senderId,loginUser.getUserId());

        int ret = friendMapper.add(loginUser.getUserId(),senderId);
        if(ret==0){
            return new Result<>(Constant.FAIL_CODE,"好友添加失败",false);
        }
        return new Result<>(Constant.SUCCESS_CODE,"好友添加成功",true);
    }

    //发送好友申请 websocket
    @RequestMapping("/addFriendApply")
    public Result<Boolean> addFriendApply(Integer receiverId,String reason,HttpServletRequest request) throws IOException {
        //拿到发送人,就是 登录 userId
        String cookie = (request.getHeader("cookie"));
        String jwtToken = cookieUtils.parseToken(cookie);
        User loginUser = jwtUtils.getUserByToken(jwtToken);
        //先看对方在不在线 如果在线 马上转发
        WebSocketSession webSocketSession = onlineUserManager.getSession(receiverId);
        if(webSocketSession!=null){
            log.error("测试!!!!");
            FriendApply friendApply = new FriendApply();
            friendApply.setReason(reason);
            friendApply.setReceiverId(receiverId);
            friendApply.setSenderId(loginUser.getUserId());
            friendApply.setSenderName(loginUser.getUserName());
            webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(friendApply)));
        }
        //插入数据库
        int ret =  friendApplyMapper.addApply(loginUser.getUserId(),receiverId,reason);
        if(ret==0){
            return new Result<>(Constant.FAIL_CODE,"好友申请添加失败",false);
        }
        return new Result<>(Constant.SUCCESS_CODE,"好友申请添加成功",true);
    }

//   获取添加好友消息列表
    @RequestMapping("/getFriendApplyList")
    public Result<List> getFriendApplyList(HttpServletRequest request){
        String JwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        User loginUser = jwtUtils.getUserByToken(JwtToken);
        List<FriendApply> list =  friendMapper.getFriendApplyList(loginUser.getUserId());
        return  new Result<>(Constant.SUCCESS_CODE,"查询好友申请列表成功",list);
    }


//    删除好友
    @RequestMapping("/deleteFriend")
    public Result<Boolean> deleteFriend(Integer sessionId,HttpServletRequest request){

//        拿到
        String JwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        User loginUser = jwtUtils.getUserByToken(JwtToken);
        Friend toUser =  sessionMapper.selectSessionFriends(sessionId,loginUser.getUserId()).get(0);
//        删好友表
        friendMapper.delete(toUser.getFriendId(),loginUser.getUserId());
        friendMapper.delete(loginUser.getUserId(),toUser.getFriendId());
//        删会话表
        sessionMapper.delete(sessionId);
//        删会话-用户表
        userSessionMapper.delete(loginUser.getUserId(),sessionId);
//        删除--message表
        messageMapper.delete(sessionId);
//
        return new Result<>(200,"删除成功",true);
    }


//    查询好友列表

    @RequestMapping("/friendList")
    public Result<List> getFriendList(HttpServletRequest request){
        User user = null;
        String jwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        user = jwtUtils.getUserByToken(jwtToken);
        if(user!=null){
            List<Friend> friendList = friendMapper.getFriendListByUserId(user.getUserId());
           // System.out.println("查询好友列表结果 - "+friendList.toString());
            return new Result<>(200,"查询成功",friendList);
        }else {
            return new Result<>(-1,"查询失败",null);
        }
    }
//    新建一个数据库表
//    查询好友申请信息

//    删除好友申请信息

//    添加好友
}
